package com.molan.molan_music.entity;



import com.molan.molan_music.enums.Gender;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * 用户表(User)实体类
 *
 * @author wj-easycode
 * @since 2023-02-11 14:39:35
 */
@Entity
@Data 
public class User implements UserDetails {
    /**
    * 用户id
    */
    @Id
    private String userId;
    /**
    * 用户名
    */
    private String username;
    /**
    * 用户昵称
    */
    private String nickName;
    /**
    * 加密后的密码
    */
    private String password;
    /**
    * 性别
    */
    @Enumerated(EnumType.STRING)
    private Gender gender;
    /**
    * 是否锁定（1-是，0-否）
    */
    private Boolean locked = false;
    /**
    * 是否可用（1-是，0-否）
    */
    @Getter(value = AccessLevel.NONE)
    private Boolean enabled = true;
    /**
    * 最后登陆ip
    */
    private String lastLoginIp;
    /**
    * 最后登录时间
    */
    private Integer lastLoginTime;
    /**
    * 创建时间
    */
    private Integer createTime;
    /**
    * 更新时间
    */
    private Integer updateTime;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "role_id"))
    private List<Role> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for (Role role : roles) {
            authorityList.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return authorityList;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !getLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}
